<template>
	<div style="display: flex;">
		<Uploader @fileclick="fileclick" :type="type" :files="files" :dataType="dataType" :limit="limit" :uploadList="uploadList" ref="uploader" :dragdrop="true" :class-name="className" @deletefile="deletefile">
			<div slot="dragdrop" v-if="$slots.dragdrop">
				<slot name="dragdrop"></slot>
			</div>
		</Uploader>
		<a v-if="type == 'image' && value && value.length > 0" class="delPic" title="删除" @click="deletefile">X</a>
		<a v-if="type == 'image' && value && value.length > 0" class="showPic" title="放大" @click="$ImagePreview(value)" @click.stop.prevent="{}"><i class="icon yanjing2"></i></a>
		<div v-if="placeholder && !value" class="placeholder">{{placeholder}}</div>
	</div>
</template>
<script>

// 由于七牛和plupload的封装不是es6模式的，所以我们自己封装了两个对应的es6包
import qiniujs from 'qiniu-js-es6';
import utils from 'hey-utils';

export default {
	props: {
		options: {
			type: Object,
			default: () => { }
		},
		type: {
			type: String,
			default: 'image'
		},
		dataType: String,
		dragdrop: {
			type: Boolean,
			default: false
		},
		value: {
			type: [Object, Array, String]
		},
		limit: Number,
		className: String,
		placeholder: {
			type: String,
			default: '点击选择需要上传的内容.'
		}
	},
	data() {
		return {
			uploadList: []
		};
	},
	computed: {
		files () {
			if(this.value){
				if(this.type == 'file'){
					return {name:this.value,url:this.value+'?imageMogr2/thumbnail/150x150>/format/jpg/blur/1x0/quality/100'}
				}else{
					return this.value+'?imageMogr2/thumbnail/150x150>/format/jpg/blur/1x0/quality/100'
				}
			}
		}
	},
	methods: {
		deletefile(index) {
			let value = null;
			if (this.type == 'images' || this.type == 'files') {
				value = utils.copy(this.value);
				value.splice(index, 1);
			} else {
				value = null;
				this.uploadList = [];
			}
			this.$emit('input', value);
		},
		init() {
			let that = this;
			// 七牛文档请参考https://developer.qiniu.com/kodo/sdk/1283/javascript
			// uploader文档请参考http://www.cnblogs.com/2050/p/3913184.html
			let param = {
				runtimes: 'html5',
				browse_button: this.$refs.uploader.getBrowseButton(),
				//uptoken_url: 'https://erp.huantu.cc/erp/uptoken',
				uptoken : this.$global.config.uptoken,
				domain: 'http://qn.huantu.cc',
				chunk_size: '2mb',
				unique_names: true,
				auto_start: false,
				filters: {},
				init: {
					FilesAdded(up, files) {
						if (that.limit && (files.length + that.value.length > that.limit)) {
							that.$Message.error(`你上传的文件超过${that.limit}个。`);
							return;
						}
						files.forEach((file) => {
							if (FileReader) {
								let reader = new FileReader();
								reader.onload = (event) => {
									file.thumbUrl = event.target.result;
								};
								reader.readAsDataURL(file.getNative());
							}
							if (that.type == 'files' || that.type == 'images') {
								that.uploadList.push(file);
							} else {
								that.uploadList = [file];
							}
						});
						up.start();
					},
					BeforeUpload(up, file) {

					},
					UploadProgress(up, file) {
						// log(file.percent);
					},
					FileUploaded(up, file, info) {
						// log('FileUploaded', file.status);
						let domain = up.getOption('domain');
						let res = JSON.parse(info.response);
						let sourceLink = `${domain}/${res.key}`; // 获取上传成功后的文件的Url
						file.url = sourceLink;
					},
					Error(up, err, errTip) {
						that.uploadList.splice(0, that.uploadList.length);
						that.$Message.error(errTip);
					},
					UploadComplete() {
						that.$emit('completeUpload');
						let fileList = that.$refs.uploader.getFileList();
						//   fileList.map(item=>{
						//     // 对返回的数据做最后的组装
						//     // item.type = 5;
						//     // item.fileType = ...
						//   })
						that.$emit('input', fileList);
						if (that.type == 'files' || that.type == 'images') {
							that.uploadList.splice(0, that.uploadList.length);
						}
					}
					// Key(up, file) {
					//     // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
					//     // 该配置必须要在unique_names: false，save_key: false时才生效
					//     var key = "";
					//     // do something with key here
					//     return key
					// }
				}
			};
			if (this.dragdrop) {
				param.dragdrop = true;
				param.drop_element = this.$refs.uploader.getDropElement();
			}

			utils.extend(param, this.options);
			let muti = this.type == 'files' || this.type == 'images';
			param.multi_selection = muti;
			qiniujs.Qiniu.uploader(param);
		},
		fileclick(file) {
			let hzm = file.url.substring(file.url.length - 4)
			if (hzm == '.doc' || hzm == '.xls' || hzm == 'docx' || hzm == 'xlsx') {
				window.open('https://view.officeapps.live.com/op/view.aspx?src='+file.url, '_blank')
			}else{
				window.open(file.url, '_blank')
			}
		}
	},
	mounted() {
		this.$nextTick(() => {
			this.init();
		});
	}
};
</script>

<style lang="less">
	.placeholder{
		position: absolute;
		display: flex;
		align-items: center;
		font-size: 14px;
		color: #999999;
		margin: 10px;
	}
	.delPic {
		position: absolute;
		z-index: 9999;
		right:0;
		background-color: #FF0000;
		color: #ffffff;
		width: 20px;
		height: 20px;
		text-align: center;
		border-radius: 0 4px 0 15px;
	}
	.showPic{
		position: absolute;
		z-index: 9999;
		bottom: 0px;
		right:0;
		background-color: #00aa00;
		color: #ffffff;
		width: 25px;
		height: 25px;
		line-height: 25px;
		text-align: center;
		border-radius:15px 0 4px 0;
		i {
			font-size:16px;
		}
	}
</style>